<template>
  <page-header-wrapper>
    <GlobalSearch :list="searchList" @search="handleSearch" @reset="handleReset"></GlobalSearch>
    <a-card :bordered="false">
      <s-table
        ref="table"
        size="default"
        rowKey="ID"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: true }"
        :pagination="{ showTotal: (total) => `共 ${total} 条` }"
      >
        <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
        <div slot="action" slot-scope="text, record">
          <y-button type="link" @click="handleDetail(record.ID)">查看</y-button>
          <y-button type="link" class="text-warning" @click="handleDistribution(record)">更换房屋</y-button>
        </div>
      </s-table>
    </a-card>
    <house-list
      ref="houseList"
      :visible.sync="visibleHouseList"
      :searchList.sync="houseSearchList"
      :loadData="loadHouseList"
      :houseParams="houseParams"
      :actions="houseActions"
      title="实物分配"
      @HoueTypeColor="handelHoueTypeColor"
    >
      <div slot="action" slot-scope="scope">{{ scope.house.ID }}</div>
    </house-list>
    <house-detail :visible.sync="visibleHouseDetail" :houseID="houseItem.ID"></house-detail>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis, houseList, houseDetail } from '@/components'
import { getChangeHouseList, postChangeHouseApplication } from '@/api/cityReviewAndManage'
import {
  getHousingEstateList,
  getHouseIdRoof,
  getHouseRoofidTotalFloor,
  getHousesXMList,
  getHouseList,
} from '@/api/common'
import moment from 'moment'

export default {
  name: 'cityComplexInquireList',
  components: {
    STable,
    Ellipsis,
    houseList,
    houseDetail,
  },
  data() {
    return {
      houseTypeOptions: [],
      queryParam: {
        Mode: 'SQ',
        strContent: {},
      },
      visibleHouseList: false,
      contractItem: {},
      visibleHouseDetail: false,
      houseItem: {},
      houseActions: [
        {
          tooltip: '更换',
          icon: 'retweet',
          show: (e) => {
            if (this.$isEmpty(this.contractItem)) return false
            const houseIDIndex = this.contractItem.EAddress.indexOf('：')
            const houseID = Number(this.contractItem.EAddress.substr(0, houseIDIndex))
            return (e.Mode === '空置' || e.Mode === '租赁中') && houseID !== e.ID
          },
          onClick: (e) => {
            this.$confirm({
              title: '提示',
              content:
                e.Mode === '租赁中'
                  ? `此房屋现居住人为：${e.Name}，确定要更换至${e.Floor}-${e.Number}该房屋`
                  : `确定要更换至${e.Floor}-${e.Number}该房屋？`,
              onOk: () => {
                return postChangeHouseApplication({
                  State: 'add',
                  ZC_HTXX: [
                    {
                      ID: this.contractItem.ID,
                      ESites: e.ID,
                    },
                  ],
                }).then((res) => {
                  this.$message.success('房屋更换申请提交成功')
                  this.visibleHouseList = false
                  this.contractItem = {}
                  this.$refs.table.refresh()
                })
              },
            })
          },
        },
        {
          tooltip: '查看',
          icon: 'eye',
          theme: 'filled',
          onClick: (e) => {
            this.houseItem = e
            this.visibleHouseDetail = true
          },
        },
      ],
      houseParams: [
        {
          label: '房屋编号',
          custom: (house, floor) => {
            return `${floor}-${house.Number}`
          },
        },
        {
          label: '房屋结构',
          key: 'fwjg',
        },
        {
          label: '房屋面积',
          key: 'Area',
        },
        {
          label: '房屋状态',
          key: 'Mode',
        },
        {
          label: '现居住人',
          key: 'Name',
          custom: (house, floor) => {
            return house.Name || '暂无居住人'
          },
        },
      ],
      houseSearchList: [
        {
          label: '房屋所属',
          fields: 'State',
          type: 'select',
          validate: [{ required: true, message: '请选择房屋所属' }],
          props: {
            placeholder: '请选择房屋所属',
            options: [],
          },
          methods: {
            change: (State) => {
              this.$refs.houseList.$searchForm.setFieldsValue({
                housesid: undefined,
                housesroofid: undefined,
                lcid: undefined,
                mode: undefined,
              })
              for (let index = 1; index <= 3; index++) {
                this.houseSearchList[index].props.options = []
                this.houseSearchList[index].props.disabled = true
              }
              if (!this.$isEmpty(State)) {
                getHousingEstateList({
                  State,
                  UserID: this.$store.getters.userid,
                }).then((res) => {
                  this.houseSearchList[1].props.options = res.map((e) => {
                    return {
                      value: e.ID,
                      label: e.NAME,
                    }
                  })
                  this.houseSearchList[1].props.disabled = false
                })
              }
            },
          },
        },
        {
          label: '小区名称',
          fields: 'housesid',
          type: 'select',
          validate: [{ required: true, message: '请选择小区' }],
          props: {
            placeholder: '请选择小区',
            options: [],
            disabled: true,
            showSearch: true,
            optionFilterProp: 'children',
          },
          methods: {
            change: (housesid) => {
              this.$refs.houseList.$searchForm.setFieldsValue({
                housesroofid: undefined,
                lcid: undefined,
                mode: undefined,
              })
              for (let index = 2; index <= 3; index++) {
                this.houseSearchList[index].props.options = []
                this.houseSearchList[index].props.disabled = true
              }
              if (!this.$isEmpty(housesid)) {
                getHouseIdRoof({ housesid }).then((res) => {
                  this.houseSearchList[2].props.options = res.map((e) => {
                    return {
                      value: e.ID,
                      label: `${e.ROOF}栋${e.UNIT}单元`,
                    }
                  })
                  this.houseSearchList[2].props.disabled = false
                })
              }
            },
          },
        },
        {
          label: '栋号',
          fields: 'housesroofid',
          type: 'select',
          validate: [{ required: true, message: '请选择栋号' }],
          props: {
            placeholder: '请选择栋号',
            options: [],
            disabled: true,
            showSearch: true,
            optionFilterProp: 'children',
          },
          methods: {
            change: (housesroofid) => {
              this.$refs.houseList.$searchForm.setFieldsValue({
                lcid: undefined,
                mode: undefined,
              })
              this.houseSearchList[3].props.options = []
              this.houseSearchList[3].props.disabled = true
              if (!this.$isEmpty(housesroofid)) {
                getHouseRoofidTotalFloor({ housesroofid }).then((res) => {
                  this.houseSearchList[3].props.options = res.map((e) => {
                    return {
                      value: e.FLOOR,
                      label: e.FLOOR + '层',
                    }
                  })
                  this.houseSearchList[3].props.disabled = false
                })
              }
            },
          },
        },
        {
          label: '楼层',
          fields: 'lcid',
          type: 'select',
          props: {
            placeholder: '请选择楼层',
            options: [],
            disabled: true,
            showSearch: true,
            optionFilterProp: 'children',
          },
        },
        {
          label: '房源状态',
          fields: 'mode',
          type: 'select',
          props: {
            placeholder: '请选择房源状态',
            options: [],
            showSearch: true,
            optionFilterProp: 'children',
          },
        },
        // {
        //   label: '跳转测试',
        //   fields: 'tzcs',
        //   type: 'select',
        //   props: {
        //     options: [
        //       { value: '3', label: '3' },
        //       { value: '4', label: '4' }
        //     ]
        //   },
        //   methods: {
        //     change: (e) => {
        //       document.getElementById(`floor-${e}`).scrollIntoView(true)
        //     }
        //   }
        // }
      ],
      searchList: [
        {
          label: '申请编号',
          fields: 'ApplyNo',
          type: 'input',
          props: {
            placeholder: '请输入申请编号',
          },
        },
        {
          label: '申请人',
          fields: 'Proposer',
          type: 'input',
          props: {
            placeholder: '请输入申请人姓名',
          },
        },
        {
          label: '身份证号',
          fields: 'IDcard',
          type: 'input',
          props: {
            placeholder: '请输入身份证号',
          },
        },
        {
          label: '房屋地址',
          fields: 'EsitesSelect',
          type: 'input',
          props: {
            placeholder: '请输入房屋地址',
          },
        },
        {
          label: '签订时间',
          fields: 'date',
          type: 'range',
          props: {
            valueFormat: 'YYYY-MM-DD',
          },
        },
      ],
      columns: [
        {
          title: '序号',
          align: 'center',
          width: '80px',
          scopedSlots: { customRender: 'index' },
        },
        {
          title: '合同编号',
          align: 'center',
          dataIndex: 'PactNo',
        },
        // {
        //   title: '申请编号',
        //   align: 'center',
        //   dataIndex: 'ApplyNo'
        // },
        {
          title: '甲方(单位)',
          align: 'center',
          dataIndex: 'UnitName',
        },
        {
          title: '乙方租户',
          align: 'center',
          dataIndex: 'Name',
        },
        {
          title: '房屋信息',
          align: 'center',
          dataIndex: 'EAddress',
          customRender: (text) => (text ? <ellipsis length={28}>{text}</ellipsis> : ''),
        },
        {
          title: '合同状态',
          align: 'center',
          dataIndex: 'Mode',
        },
        // {
        //   title: '合同类型',
        //   align: 'center',
        //   dataIndex: 'PactClass'
        // },
        // {
        //   title: '合同状态',
        //   align: 'center',
        //   dataIndex: 'Status',
        //   customRender: (text) => {
        //     const textColor = new Map([
        //       ['已签', 'text-success'],
        //       ['待签', 'text-warning'],
        //       ['续签', 'text-primary'],
        //       ['过期', 'text-error']
        //     ])
        //     return <span class={textColor.get(text)}>{text}</span>
        //   }
        // },
        {
          title: '起租日期',
          align: 'center',
          dataIndex: 'StartDate',
          customRender: (text) => moment(text).format('YYYY-MM-DD'),
        },
        {
          title: '止租日期',
          align: 'center',
          dataIndex: 'EndDate',
          customRender: (text) => moment(text).format('YYYY-MM-DD'),
        },
        {
          title: '签订日期',
          align: 'center',
          dataIndex: 'SignDate',
          customRender: (text) => moment(text).format('YYYY-MM-DD'),
        },
        // {
        //   title: '经办人',
        //   align: 'center',
        //   dataIndex: 'Operator',
        //   customRender: (text) => text || '/'
        // },
        {
          title: '操作',
          align: 'center',
          width: '180px',
          fixed: 'right',
          scopedSlots: { customRender: 'action' },
        },
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getChangeHouseList(requestParameters).then((res) => res)
      },
      loadHouseList: (parameter, strContent) => {
        if (this.$isEmpty(strContent)) {
          return Promise.resolve({
            data: [],
            count: 0,
          })
        }
        const { mode, lcid, housesroofid, housesid } = strContent
        return getHouseList({
          ...parameter,
          mode: mode || '',
          lcid: lcid || '',
          housesroofid: housesroofid || '',
          housesid: housesid || '',
        }).then((res) => res)
      },
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      const getHouseXm = getHousesXMList({
        UserID: this.$store.getters.userid,
      })
      Promise.all([getHouseXm]).then((res) => {
        this.houseSearchList[0].props.options = res[0].map((e) => {
          return {
            value: e.VALUES,
            label: e.NAME,
          }
        })
      })
    },
    handleSearch(values) {
      const { date } = values
      if (!this.$isEmpty(date)) {
        values.EsetDate = date[0]
        values.EndTime = date[1]
      }
      delete values.date
      this.queryParam.strContent = values
      this.$refs.table.refresh(true)
    },
    handleReset() {
      this.queryParam.strContent = {}
      this.$refs.table.refresh(true)
    },
    handleDetail(id) {
      localStorage.setItem('browserCacheDetail', JSON.stringify({ id: id }))
      this.$router.push({
        name: 'cityChangeHouseApplicationDetail',
        params: {
          id,
        },
      })
    },
    handleDistribution(record) {
      this.contractItem = record
      this.visibleHouseList = true
    },
    handelHoueTypeColor(options) {
      this.houseTypeOptions = options
      this.houseSearchList[4].props.options = this.houseTypeOptions
    },
  },
}
</script>
<style lang="less" scoped>
.table-header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
/deep/ .ant-table td {
  white-space: nowrap;
}
</style>
